//
//  AppDelegate+Ext+Notification.swift
//  Runner
//
//  Created by 雪儿 on 2025/5/27.
//

import Foundation
import AdjustSdk
import business_plugin // 导入插件

extension AppDelegate: AdjustDelegate {
    //获取通知权限
    func getNotification(){
        let userNotificationCenter:UNUserNotificationCenter = UNUserNotificationCenter.current()
        userNotificationCenter.delegate = self
        //静默推送不需要权限
        UIApplication.shared.registerForRemoteNotifications();
    }
    
    override func application(
        _ application: UIApplication,
        didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            // 将设备令牌传递给 Adjust SDK
            Adjust.setPushToken(deviceToken);
            // 2. 将令牌传递给 Flutter 插件
            BusinessPlugin.setPushToken(token: deviceToken)
            let deviceTokenString = deviceToken.map { String(format: "%02x", $0) }.joined()
            print("deviceTokenString:", deviceTokenString)
        }
    
    // 添加失败回调方法
    override func application(
        _ application: UIApplication,
        didFailToRegisterForRemoteNotificationsWithError error: Error) {
            print("注册远程通知失败: \(error)")
        }
    
    //静默推送
    override func application(
        _ application: UIApplication,
        didReceiveRemoteNotification userInfo: [AnyHashable: Any],
        fetchCompletionHandler completionHandler: @escaping (
            UIBackgroundFetchResult) -> Void) {
                if let adjustPurpose = userInfo["adjust_purpose"] as? String,
                   adjustPurpose == "uninstall detection" {
                    // 处理 Adjust 卸载检测的特殊负载
                    completionHandler(.noData)
                } else {
                    // 处理普通推送通知
                    completionHandler(.newData)
                }
            }

    //静默推送:iOS7之前调用此方法
    override  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        print("收到了静默推送通知2: \(userInfo)");
    }
}
